package net.pimpas.persistence.hibernate.scanner;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import net.pimpas.core.configuration.file.FileConfiguration;
import net.pimpas.core.configuration.file.FileConfigurationImpl;
import net.pimpas.core.scanner.Scanner;
import net.pimpas.core.scanner.exception.ScannerException;
import net.pimpas.logging.serviceprovider.LoggingServiceProvider;
import net.pimpas.logging.serviceprovider.LoggingServiceProviderFactoryImpl;

public class HibernateConfigScanner implements Scanner<FileConfiguration> {
	
	private List<FileConfiguration> result;
	
	private static final LoggingServiceProvider logger = 
		LoggingServiceProviderFactoryImpl.getLoggingServiceProvider(HibernateConfigScanner.class);
	
	public HibernateConfigScanner() {
		this.setResult(new ArrayList<FileConfiguration>());
	}

	public String getName() {
		return "[Hibernate Scanner]";
	}

	public List<FileConfiguration> getResult() {
		return this.result;
	}

	public void scan() throws ScannerException {
		logger.debug("Looking for configuration file: pimpas-hibernate-config.xml");
		URL url = this.getClass().getClassLoader().getResource("pimpas-hibernate-config.xml");
		if(url== null) {
			// try default
			url = this.getClass().getClassLoader().getResource("pimpas-hibernate-config-default.xml");
			if(url == null)
				// error
				throw new ScannerException("Cannot FIND Hibernate Configuration File");
			logger.info("[PERSISTENCEHIBERNATE]: File pimpas-hibernate-config.xml not found, using default!");
		}
		
		InputStream stream = null;
		try {
			stream = url.openStream();
			logger.debug("Setting Hibernate Configuration File: "+url.getFile());
			
			FileConfiguration fc = new FileConfigurationImpl(url, stream);
			this.getResult().add(fc);
		} catch (IOException e) {
			throw new ScannerException(e);
		}
	}

	public void setResult(List<FileConfiguration> result) {
		this.result = result;
	}
}